package com.linkkap.feishu.api.helper;

import java.io.IOException;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import lombok.extern.slf4j.Slf4j;

/**
 * @author ??
 */
@Slf4j
@Component
public class FeiShuHelper {

	public static String httpRestClient(String url, HttpMethod method, JSONObject json) throws IOException {
		return httpRestClient(url,method,json,null);
	}
    public static String httpRestClient(String url, HttpMethod method, JSONObject json, String token) throws IOException {
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setConnectTimeout(10*1000);
        requestFactory.setReadTimeout(10*1000);
        RestTemplate client = new RestTemplate(requestFactory);
        
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        if(token != null) {
            headers.setBearerAuth(token);
        }
        log.debug("post请求:", json);
        HttpEntity<String> requestEntity = new HttpEntity<String>(json.toString(), headers);
        
        //  执行HTTP请求
        ResponseEntity<String> response = client.exchange(url, method, requestEntity, String.class);
        return response.getBody();
    }
    public static void sendContentMessage(String accessToken,String openId,String text) throws IOException {
    	
    	String url = "https://open.feishu.cn/open-apis/message/v4/send/";
    	
    	JSONObject json = new JSONObject();
    	 json.put("open_id", openId);
    	 json.put("msg_type", "text");
    	 
    	 JSONObject content = new JSONObject();
    	 content.put("text", text);
    	 
    	 json.put("content", content);
    	 
         //发送http请求并返回结果
    	 HttpMethod method =HttpMethod.POST;
         log.debug(""+json);
         String result = httpRestClient(url,method,json,accessToken);
         
         log.info("飞书发送信息给用户，返回信息为："+result);
         
         JSONObject jsonParam = JSON.parseObject(result);
         int code = jsonParam.getIntValue("code");
         if(code != 0) {
         	throw new IOException("飞书发送信息给用户异常.");
         }        
    }
    /**
     * 可以直接发送打包好的json String数据
     * */
    public static void sendContentMessage(String accessToken, String text) throws IOException{
        String url = "https://open.feishu.cn/open-apis/message/v4/send/";
        //发送http请求并返回结果
        HttpMethod method =HttpMethod.POST;
        JSONObject request = JSON.parseObject(text);
        log.debug(""+request);
        String result = httpRestClient(url, method, request,accessToken);

        log.info("飞书发送信息给用户，返回信息为："+result);

        JSONObject jsonParam = JSON.parseObject(result);
        int code = jsonParam.getIntValue("code");
        if(code != 0) {
            throw new IOException("飞书发送信息给用户异常.");
        }
    }

    public static void sendCardMessage(String accessToken,String openId,String text) throws IOException {
    	
    	String url = "https://open.feishu.cn/open-apis/message/v4/send/";
    	
    	JSONObject json = new JSONObject();
    	 json.put("open_id", openId);
    	 json.put("msg_type", "interactive");
    	 
    	 JSONObject card = JSON.parseObject(text);
    	 
    	 json.put("card", card);
    	 
         //发送http请求并返回结果
    	 HttpMethod method =HttpMethod.POST;
         String result = httpRestClient(url,method,json,accessToken);
         
         log.info("飞书发送信息给用户，返回信息为："+result);
         
         JSONObject jsonParam = JSON.parseObject(result);
         int code = jsonParam.getIntValue("code");
         if(code != 0) {
         	throw new IOException("飞书发送信息给用户异常.");
         }        
    }    
	public static String getTenantAccessToken(String appId, String appSerect) throws IOException {
		
		String url = "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal/";

        //post请求
        HttpMethod method =HttpMethod.POST;
        JSONObject json = new JSONObject();
        json.put("app_id", appId);
        json.put("app_secret", appSerect);
        
        //发送http请求并返回结果
        String result = httpRestClient(url,method,json);
        
        log.info("请求飞书token，返回信息为："+result);
        
        JSONObject jsonParam = JSON.parseObject(result);
        int code = jsonParam.getIntValue("code");
        if(code != 0) {
        	throw new IOException("获取access_token异常.");
        }
        String tenantAccessToken = jsonParam.getString("tenant_access_token");
        return tenantAccessToken;
	}
}
